package com.byCreation.t_globe;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import weatherdataAPI.Weather;

import com.aretha.slidemenu.SlideMenu;


import com.byCreatetion.adabter.DiscountAdapter;
import com.byCreatetion.adabter.NoteAdapter;
import com.byCreatetion.adabter.NotificationAdapter;

import com.byCreation.Control.Control;
import com.byCreation.Control.MenuData;
import com.byCreation.Control.SliderMenuLeft;
import com.byCreation.Profile.*;
import com.byCreation.t_globe.R;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.model.LatLng;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.squareup.picasso.Picasso;

import FileIO.ReadWrite;
import Myclass.ConnectInternet;
import Parser.HttpGetJson;
import Parser.SendToBD;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.StrictMode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.SlidingDrawer.OnDrawerScrollListener;

public class MainActivity extends BaseSlideMenuActivity implements
		OnClickListener, OnDrawerScrollListener, AnimationListener
	,ConnectionCallbacks, OnConnectionFailedListener, LocationListener  {

	
	
	
	   // ===============GoogleAnalytics==============
		private GoogleAnalytics mGaInstance;
		private Tracker mGaTracker;
		// =============================================
	
	
	
	private int[] iconwather={R.drawable.a01d,
			R.drawable.a01n,
			R.drawable.a02d,
			R.drawable.a02n,
			R.drawable.a03d,
			R.drawable.a03n,
			R.drawable.a04d,
			R.drawable.a04n,
			R.drawable.a06d,
			R.drawable.a06n,
			R.drawable.a10d,
			R.drawable.a10n,
			R.drawable.a11d,
			R.drawable.a11n,
			R.drawable.a13d,
			R.drawable.a13n,
			R.drawable.a50d,
			R.drawable.a50n};
	
	private String[] string_iconwather={"01d",
			"01n",
			"02d",
			"02n",
			"03d",
			"03n",
			"04d",
			"04n",
			"06d",
			"06n",
			"10d",
			"10n",
			"11d",
			"11n",
			"13d",
			"13n",
			"50d",
			"50n"};
	
	
	 
 //private String[] page_id={"3006","14396","3536","7709"};
 //private String[] page_Content_menutitle={"เกาะพะงัน","ฟูลมูนปาร์ตี้","หาดริ้นใน","หาดยาวเกาะพะงัน"};

 

		@Override
		public void onStop() {
			super.onStop();
			// The rest of your onStop() code.
			EasyTracker.getInstance().activityStop(this); // Add this method.

		}
		// ===================================googleAnalytics=============================
		@Override
		public void onStart() {
			super.onStart();
			// The rest of your onStart() code.
			EasyTracker.getInstance().activityStart(this); // Add this method.

			mGaTracker.sendView("HomeScreen");

		}
		// ================================================================================

	
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		
		Control.page_id=Control.Current_id;
		SliderMenuLeft.Content_title=SliderMenuLeft.Mainmenu_page_title;
		Log.e("tglobe", "=========onRestart() ==========");
		slide.ReSetMainMenu();
		
		
		if (Control.Loginstatus)
		{
			Log.e("Picasso", "=========Picasso()  onRestart ==========");
			
//			Picasso.with(this)
//			.load(new File(Control.Img_profile_Path))
//			.placeholder(R.drawable.btn_menu_top_righ)
//			.error(R.drawable.btn_menu_top_righ)
//			.into(img_profile);
			
			final Handler handler=new Handler();
			final Runnable r = new Runnable()
			{
			    public void run() 
			    {
			    	try {
						
						
						
						Log.e("Picasso", "=========Picasso() ==========");
						
						if(Control.Img_profile.equals(""))
						{
							img_profile.setImageResource(R.drawable.btn_menu_top_righ);
							img_user.setImageResource(R.drawable.btn_menu_top_righ);

						}
						else
						{
							Bitmap myBitmap = BitmapFactory.decodeFile(Control.Img_profile_Path);
							img_profile.setImageBitmap(myBitmap);
							img_user.setImageBitmap(myBitmap);

						}
						
						
						
						} catch (Exception e) {
							img_profile.setImageResource(R.drawable.btn_menu_top_righ);
							img_user.setImageResource(R.drawable.btn_menu_top_righ);

						}
			    }
			};

			handler.postDelayed(r, 2000);
			
			
		}
		
		super.onRestart();
	}


	public FrameLayout lay_munu;
	private SlidingDrawer drawer;
	ImageView img_next_content, img_back_content;

	private FrameLayout Lay_content0, Lay_content1, Lay_content2, Lay_content3;
	private ImageView img1, img2, img3, img4;
	private TextView txt_title1,txt_title2,txt_title3,txt_title4;
	private TextView txt_subtitle1,txt_subtitle2,txt_subtitle3,txt_subtitle4;
	
	
	private int indexPage = 0;
	private int indexAll = 3;
	private boolean next = true;

	private FrameLayout[] Lay_content = { Lay_content0, Lay_content1,Lay_content2, Lay_content3 };
	private ImageView[] img_Cover = { img1, img2,img3, img4 };
	private TextView[] txt_title = { txt_title1,txt_title2,txt_title3,txt_title4};
	private TextView[] txt_subtitle = { txt_subtitle1,txt_subtitle2,txt_subtitle3,txt_subtitle4};

	

	// Animation
	Animation animSlide_R, animSlide_L;

	// ======Down menu
	private ViewFlipper handle;
	private ImageView img_fame0;

	// SliderMenu
	private SlideMenu mSlideMenu;

	// Profile
	private ImageView img_profile_menu1, img_profile_menu2, img_profile_menu3,
			img_profile_menu4, img_profile_menu5, img_profile_menu6,
			img_profile_menu7, img_profile_menu8, img_profile_menu9, img_user;

	private LinearLayout txt_next, txt_register;
	private FrameLayout Laylogin;
	private ConnectInternet connect = new ConnectInternet(MainActivity.this);

	
	
	private  Weather  weather;
	
	
	@Override
	public void onContentChanged() {
		super.onContentChanged();
		Log.e("Test", "SlideMenuAttribute");
		setSlideRole(R.layout.activity_main);
		setSlideRole(R.layout.layout_primary_menu);
		setSlideRole(R.layout.fagment_profile);
		
		// =============================GoogleAnalytics=========================
		mGaInstance = GoogleAnalytics.getInstance(this);
		mGaTracker = mGaInstance.getTracker(Control.IDGoogleanalytics);
		
		
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}

		
		Control.UserName=Control.UserName.replace(" ", "%20");
		SetView();
		SetViewProfile();
		if(new ConnectInternet(this).checkInternetConnection())
			new Laod_API_MainMenuCover().execute();
		
		
		
		
		
		
		
		
	}
	SliderMenuLeft slide;
	private void SetSliderMenu() {
		// TODO Auto-generated method stub
		mSlideMenu = getSlideMenu();

		mSlideMenu.setEdgeSlideEnable(true);
		mSlideMenu.setEdgetSlideWidth(Control.setEdgetSlideWidth);
		Display display = getWindowManager().getDefaultDisplay();
		int width = display.getWidth(); // deprecated
		int height = display.getHeight(); // deprecated

		
		RelativeLayout rl = (RelativeLayout) findViewById(R.id.R1);
		RelativeLayout r2 = (RelativeLayout) findViewById(R.id.R2);

		rl.getLayoutParams().width = width - 100;
		r2.getLayoutParams().width = width - 100;
		slide=new SliderMenuLeft(this,true,mSlideMenu);
		
	}
	
	ImageView img_profile ;
	private void SetView() {
		// TODO Auto-generated method stub

		lay_munu = (FrameLayout) findViewById(R.id.lay_munu);
		lay_munu.setVisibility(View.INVISIBLE);
		
		lay_munu.setVisibility(View.VISIBLE);
		Animation animmenu= AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.anim_menu_in);
		lay_munu.startAnimation(animmenu);
		
		

		ImageView img_content = (ImageView) findViewById(R.id.img_content);
		ImageView img_mainmenu = (ImageView) findViewById(R.id.img_mainmenu);
		 img_profile = (ImageView) findViewById(R.id.img_profile);
		img_fame0 = (ImageView) findViewById(R.id.img_fame0);

		if (Control.Loginstatus)
		{
			try {
				
			
			
			Log.e("Picasso", "=========Picasso() ==========");
			
			if(Control.Img_profile.equals(""))
			{
				img_profile.setImageResource(R.drawable.btn_menu_top_righ);

			}
			else
			{
				try {
					
					
					
					Log.e("Picasso", "=========Picasso() ==========");
					
					if(Control.Img_profile.equals(""))
					{
						img_profile.setImageResource(R.drawable.btn_menu_top_righ);

					}
					else
					{
						Bitmap myBitmap = BitmapFactory.decodeFile(Control.Img_profile_Path);
						img_profile.setImageBitmap(myBitmap);

					}
					
					
					
					} catch (Exception e) {
						img_profile.setImageResource(R.drawable.btn_menu_top_righ);

					}
			}
			
			
			
			} catch (Exception e) {
				img_profile.setImageResource(R.drawable.btn_menu_top_righ);
			}
		}
			
		img_profile.setOnClickListener(this);
		img_mainmenu.setOnClickListener(this);
		img_content.setOnClickListener(this);

		img_next_content = (ImageView) findViewById(R.id.img_next_content);
		img_next_content.setOnClickListener(this);
		img_back_content = (ImageView) findViewById(R.id.img_back_content);
		img_back_content.setOnClickListener(this);
		img_back_content.setVisibility(View.INVISIBLE);
		

		Lay_content[0] = (FrameLayout) findViewById(R.id.Lay_content0);
		Lay_content[1] = (FrameLayout) findViewById(R.id.Lay_content1);
		Lay_content[2] = (FrameLayout) findViewById(R.id.Lay_content2);
		Lay_content[3] = (FrameLayout) findViewById(R.id.Lay_content3);

		
		img_Cover[0] = (ImageView) findViewById(R.id.img_bg1);
		img_Cover[1] = (ImageView) findViewById(R.id.img_bg2);
		img_Cover[2] = (ImageView) findViewById(R.id.img_bg3);
		img_Cover[3] = (ImageView) findViewById(R.id.img_bg4);
		
	
		txt_title[0] = (TextView) findViewById(R.id.txt_title1);
		txt_title[1] = (TextView) findViewById(R.id.txt_title2);
		txt_title[2] = (TextView) findViewById(R.id.txt_title3);
		txt_title[3] = (TextView) findViewById(R.id.txt_title4);

		txt_subtitle[0] = (TextView) findViewById(R.id.txt_subtitle1);
		txt_subtitle[1] = (TextView) findViewById(R.id.txt_subtitle2);
		txt_subtitle[2] = (TextView) findViewById(R.id.txt_subtitle3);
		txt_subtitle[3] = (TextView) findViewById(R.id.txt_subtitle4);

		
		
		
		
		// =====Downmenu
		handle = (ViewFlipper) findViewById(R.id.viewFlipper1);
		ImageView img_cross_dash = (ImageView) findViewById(R.id.img_cross_dash);
		img_cross_dash.setOnClickListener(this);

		SetSlidingDrawer();

	}

	
	// ==================ListView======================
	private ListView lstView_notis;
	private NotificationAdapter adapter_notis;
	public ArrayList<HashMap<String, Object>> MyArrList_notis;
	private HashMap<String, Object> map_notis = new HashMap<String, Object>();
	private ProgressDialog mProgressDialog_notis;
	private void setListview_notis()
	{
		

		lstView_notis = (ListView)findViewById(R.id.list_view_notis);
		this.setProgressBarIndeterminateVisibility(true);
		lstView_notis.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				
			}
		});
		 //=====================ProgressDialog==========================
		if(mProgressDialog_notis==null)
		{
	        mProgressDialog_notis = new ProgressDialog(this);
	        mProgressDialog_notis.setProgressStyle(ProgressDialog.STYLE_SPINNER);         
	        mProgressDialog_notis.setMessage("Loading......");                       
	        mProgressDialog_notis.setCancelable(false);  
			MyArrList_notis = new ArrayList<HashMap<String, Object>>();

		}
	


	
		if(new ConnectInternet(getBaseContext()).checkInternetConnection())
			new LoadData_Notification().execute();
	
		
		
		
	}
	
	@SuppressWarnings("deprecation")
	private void SetSlidingDrawer() {
		// TODO Auto-generated method stub
		// ==========SlideDown
		drawer = (SlidingDrawer) findViewById(R.id.drawer);
		drawer.setOnDrawerScrollListener(this);

		drawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {
			@Override
			public void onDrawerOpened() {
				Log.e("TG", "setOnDrawerOpen");

				handle.setBackgroundResource(R.drawable.dashboard_top_bar);
				img_fame0.setVisibility(View.INVISIBLE);
				handle.stopFlipping();
			}
		});

		drawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {
			@Override
			public void onDrawerClosed() {
				Log.e("TG", "setOnDrawerClose");
				img_fame0.setVisibility(View.VISIBLE);
				handle.setBackgroundColor(Color.parseColor("#00efefef"));
				handle.startFlipping();
			}
		});
		
		
		TextView txt_name=(TextView)findViewById(R.id.txt_name);
		txt_name.setText("Hi,"+Control.UserName);
		
		
		
		DateFormat df = new SimpleDateFormat("MMM d,EEE");
		String date = df.format(Calendar.getInstance().getTime());
		
		TextView txt_day=(TextView)findViewById(R.id.txt_day);
		txt_day.setText(date);
		
		
		
		

	}

	
	private ArrayList<String> listPage_ID=new ArrayList<String>();
	private ArrayList<String> listPage_Content_menutitle=new ArrayList<String>();
	private ArrayList<String> listPage_img=new ArrayList<String>();
	private ArrayList<String> listPage_menuSubtitle=new ArrayList<String>();
	
	class Laod_API_MainMenuCover extends AsyncTask<Object, Integer, Object> {

	    private ProgressDialog mProgressDialog;
		private String desc;
		private boolean Cancle=false;
			
			
			
			
			  @Override
			protected void onCancelled() {
				// TODO Auto-generated method stub
				  Cancle=true;
				super.onCancelled();
			}
		
		@SuppressWarnings("null")
		@Override
		protected Object doInBackground(Object... params) {

			try {
				JSONObject jsonObj=null;
				jsonObj = new JSONObject(HttpGetJson.GetJson(Control.getAPI_MainMenuCover(Control.UserName),Control.user,Control.pass));
				
				
				
				JSONArray jsonarray_data=jsonObj.getJSONArray("mainmenu");
				 for (int i = 0; i <jsonarray_data.length(); i++)
				 { 
					 
					
					 JSONObject jsonObj_data=jsonarray_data.getJSONObject(i);

					 

					 Log.e("TG","page_id:"+jsonObj_data.getString("page_id"));
					 Log.e("TG","images:"+jsonObj_data.getString("images"));
					 Log.e("TG","title:"+jsonObj_data.getString("title"));
					 Log.e("TG","subtitle:"+jsonObj_data.getString("subtitle"));

					 listPage_ID.add(jsonObj_data.getString("page_id"));
					 listPage_Content_menutitle.add(jsonObj_data.getString("title"));
					 listPage_img.add(jsonObj_data.getString("images"));
					 listPage_menuSubtitle.add(jsonObj_data.getString("subtitle"));
					 
					 if(i==0)
					 {
						 	Control.page_id=jsonObj_data.getString("page_id");
						 	Control.Current_id=jsonObj_data.getString("page_id");
					 }
					 
				 }
				
				
				
				try {
					desc=jsonObj.getString("desc");
				} catch (JSONException e) {
					// TODO: handle exception
				}
				
		  
		    
		    
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			desc=e.getMessage();
			e.printStackTrace();
		}catch (Exception e) {
			desc=e.getMessage();
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
				 
			return null;
		}

		@Override
		protected void onPreExecute() {

			 //=====================ProgressDialog==========================
	        mProgressDialog = new ProgressDialog(MainActivity.this);
	        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);         
	        mProgressDialog.setMessage("Loading......");                       
	    	mProgressDialog.setCancelable(true);
		
			
			if(mProgressDialog!=null)
				mProgressDialog.show();
			
			
			
			super.onPreExecute();
		}

		@Override
		public void onProgressUpdate(Integer... progress) {

			Log.e("star", "progressupdate");
			
			
		}

		@Override
		protected void onPostExecute(Object result) {

		if(!Cancle)
		{
			
			
			indexAll=listPage_ID.size()-1;
			SliderMenuLeft.Mainmenu_page_title=listPage_Content_menutitle.get(indexPage);
			SliderMenuLeft.Content_title=listPage_Content_menutitle.get(indexPage);
			Control.Current_id=listPage_ID.get(indexPage);
			
			Log.e("TG","listPage_ID.size():"+listPage_ID.size());
			SetCoverPage();
			
			
			
		}
		else
			Toast.makeText(MainActivity.this, desc, 1800).show();

		

			if(mProgressDialog!=null)
				mProgressDialog.hide();
			}
		

	}
	
	
	private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private DisplayImageOptions options;
	private void SetCoverPage() {
		// TODO Auto-generated method stub
		options = new DisplayImageOptions.Builder()
		.showStubImage(R.drawable.bg_login)
		.showImageForEmptyUri(R.drawable.bg_login)
		.showImageOnFail(R.drawable.bg_login).delayBeforeLoading(100)
		.cacheInMemory().cacheOnDisc()
		.bitmapConfig(Bitmap.Config.RGB_565)
		.displayer(new RoundedBitmapDisplayer(0)).build();
		initImageLoader(MainActivity.this);
		
		
		
		for (int i = 0; i < listPage_img.size(); i++) {
			if(i<txt_title.length-1)
		//	Picasso.with(this).load(listPage_img.get(i)).into(img_Cover[i]);
			
			
//			Picasso.with(this)
//		    .load(listPage_img.get(i))
//		    .placeholder(R.drawable.ic_launcher)
//		    .error(R.drawable.ic_launcher)
//		    .into(img_Cover[i]);
			
			try {
				imageLoader.displayImage(listPage_img.get(i),img_Cover[i], options,animateFirstListener);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			
			txt_title[i].setText(listPage_Content_menutitle.get(i));
			txt_subtitle[i].setText(listPage_menuSubtitle.get(i)); 
		}
		
		SetSliderMenu();
	}
	public void initImageLoader(Context context) {
		// This configuration tuning is custom. You can tune every option, you
		// may tune some of them,
		// or you can create default configuration by
		// ImageLoaderConfiguration.createDefault(this);
		// method.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context)
				.memoryCacheExtraOptions(800, 480)
				// default = device screen dimensions
				.threadPoolSize(3)
				// default
				.threadPriority(Thread.NORM_PRIORITY - 1)
				// default
				.tasksProcessingOrder(QueueProcessingType.FIFO)
				// default
				.denyCacheImageMultipleSizesInMemory()
				.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
				.memoryCacheSize(2 * 1024 * 1024)
				.discCacheSize(50 * 1024 * 1024).discCacheFileCount(100)
				.discCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
				.imageDownloader(new BaseImageDownloader(context)) // default

				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
	}
	@SuppressWarnings("unused")
	private static class AnimateFirstDisplayListener extends
			SimpleImageLoadingListener {

		final static List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view,
				Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				//if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 1200);
					//displayedImages.add(imageUri);
				//}
			}
		}
	}	
	
	
	
	
	
	//==========MyLocation
	  private LocationClient mLocationClient;

	private static final LocationRequest REQUEST = LocationRequest.create()
		      .setInterval(5000)         // 5 seconds
		      .setFastestInterval(20)    // 16ms = 60fps
		      .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
	
	  @Override
	  protected void onResume() {
	    super.onResume();
	
	    setUpLocationClientIfNeeded();
	    mLocationClient.connect();
	  }
	  private void setUpLocationClientIfNeeded() {
		    if (mLocationClient == null) {
		      mLocationClient = new LocationClient(
		          getApplicationContext(),
		          this,  // ConnectionCallbacks
		          this); // OnConnectionFailedListener
		    }
		  }

	  @Override
	  public void onPause() {
	    super.onPause();
	    if (mLocationClient != null) {
	      mLocationClient.disconnect();
	    }
	  }
	  
	  private LatLng MyLocation;
	  public void showMyLocation(View view) {
		    if (mLocationClient != null && mLocationClient.isConnected()) {
		      String msg = "Location = " + mLocationClient.getLastLocation();
		     // Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
		    }
		  }

		  /**
		   * Implementation of {@link LocationListener}.
		   */
		  @Override
		  public void onLocationChanged(Location location) {
			  MyLocation=new LatLng(location.getLatitude(),location.getLongitude());


				WeatherSet(location);
			  
		  }
		  
		  private void WeatherSet(Location location) {
			// TODO Auto-generated method stub
			  
			  if(weather==null)
				  weather=new Weather(MainActivity.this, MyLocation.latitude, MyLocation.longitude);

			  TextView txt_tempo=(TextView)findViewById(R.id.txt_tempo);
				txt_tempo.setText(""+weather.temp+"C");
				
				
				TextView txt_location=(TextView)findViewById(R.id.txt_location);
				txt_location.setText(weather.Location);
				
				TextView txt_humidity=(TextView)findViewById(R.id.txt_humidity);
				txt_humidity.setText(weather.humidity);
				
				TextView txt_rain=(TextView)findViewById(R.id.txt_rain);
				txt_rain.setText(weather.rain);
				
				TextView txt_pressure=(TextView)findViewById(R.id.txt_pressure);
				txt_pressure.setText(weather.pressure);
				
				
				TextView txt_wind_speed=(TextView)findViewById(R.id.txt_wind_speed);
				txt_wind_speed.setText(weather.wind_speed+"mps");
				
				
				
				String directions[] = {"N", "NE", "E", "SE", "S", "SW", "NW",""};
			 
				
				TextView txt_wind_deg=(TextView)findViewById(R.id.txt_wind_deg);
				txt_wind_deg.setText( directions[ (int)Math.round((  ((weather.wind_deg) % 360) / 45)) ]);
				
				ImageView img_icon_tempo=(ImageView)findViewById(R.id.img_icon_tempo);
			
				
				
				for (int i = 0; i < string_iconwather.length; i++) {
					if(string_iconwather[i].equals(weather.weather_icon));
					img_icon_tempo.setImageResource(iconwather[i]);
					
				}
				
				
		}
		  

		  /**
		   * Callback called when connected to GCore. Implementation of {@link ConnectionCallbacks}.
		   */
		  @Override
		  public void onConnected(Bundle connectionHint) {
		    mLocationClient.requestLocationUpdates(
		        REQUEST,
		        this);  // LocationListener
		     // Toast.makeText(getApplicationContext(), "Connext", Toast.LENGTH_SHORT).show();

		  }

		  /**
		   * Callback called when disconnected from GCore. Implementation of {@link ConnectionCallbacks}.
		   */
		  @Override
		  public void onDisconnected() {
		    // Do nothing
		     // Toast.makeText(getApplicationContext(), "onDisconnected", Toast.LENGTH_SHORT).show();

		  }

		  /**
		   * Implementation of {@link OnConnectionFailedListener}.
		   */
		  @Override
		  public void onConnectionFailed(ConnectionResult result) {
		    // Do nothing
		      Toast.makeText(getApplicationContext(), "onConnectionFailed", Toast.LENGTH_SHORT).show();

		  }
	
	
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.img_content) {
			// finish();
			
			SliderMenuLeft.Mainmenu_List_DATA_History.clear();
			SliderMenuLeft.Mainmenu_List_Menu_Title.clear();
			SliderMenuLeft.Mainmenu_page_title=listPage_Content_menutitle.get(indexPage);
			SliderMenuLeft.Content_title=listPage_Content_menutitle.get(indexPage);
			//Control.Current_id=page_id[indexPage];
			Control.page_id=listPage_ID.get(indexPage);

			
			
			Log.e("TG", "Control.Current_id:"+Control.Current_id);

			SliderMenuLeft.Mainmenu_List_Menu_Title.add(SliderMenuLeft.Mainmenu_page_title);
			startActivity(new Intent(MainActivity.this, ContentActivity.class));
			overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
			
		
			
			
		} else if (v.getId() == R.id.img_profile) {
			mSlideMenu.open_R(true, true);

		} else if (v.getId() == R.id.img_mainmenu) {
			mSlideMenu.open_L(true, true);

		}

		if (v.getId() == R.id.img_cross_dash) {
			drawer.close();
		}

		if (v.getId() == R.id.img_next_content && indexPage < indexAll) {

			Log.e("YG", "index=" + indexPage);
			next = true;

			AnimationSet as = new AnimationSet(true);

			ScaleAnimation anim_scale = new ScaleAnimation(1.0f, 0.0f, 1.0f,
					1.0f, Animation.RELATIVE_TO_SELF, 0.0f,
					Animation.RELATIVE_TO_SELF, 0.0f);
			anim_scale.setDuration(200);

			Animation anim_alpha = new AlphaAnimation(1.0f, 0.0f);
			anim_alpha.setDuration(125);
			anim_alpha.setStartOffset(125);

			as.addAnimation(anim_scale);
			// as.addAnimation(anim_alpha);
			as.setAnimationListener(this);

			Lay_content[indexPage].startAnimation(as);

			Log.e("TG", "listPage_ID.get(indexPage):"+listPage_ID.get(indexPage));


			// Lay_content[indexPage].startAnimation(animSlide_R);

		} else if (v.getId() == R.id.img_back_content && indexPage > 0) {

			Log.e("YG", "index=" + indexPage);
			next = false;

			Lay_content[indexPage - 1].setVisibility(View.VISIBLE);
			ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 1.0f, 1.0f,
					Animation.RELATIVE_TO_SELF, 0.0f,
					Animation.RELATIVE_TO_SELF, 0.0f);
			anim.setDuration(200);
			anim.setAnimationListener(this);
			Lay_content[indexPage - 1].startAnimation(anim);
			
			Log.e("TG", "listPage_ID.get(indexPage):"+listPage_ID.get(indexPage));


		}

		// ======Profile
		// //================Menu==============
		if (v.getId() == R.id.img_profile_menu1) {
			startActivity(new Intent(MainActivity.this, MyHistoryActivity.class));
		}
		if (v.getId() == R.id.img_profile_menu2) {
			startActivity(new Intent(MainActivity.this,
					MyBookmarkActivity.class));
		}
		if (v.getId() == R.id.img_profile_menu3) {
			startActivity(new Intent(MainActivity.this, MyNoteActivity.class));
		}
		if (v.getId() == R.id.img_profile_menu4) {
			// startActivity(new
			// Intent(MainActivity.this,MyCompareActivity.class));
			startActivity(new Intent(MainActivity.this, CompareActivity.class));

		}
		if (v.getId() == R.id.img_profile_menu5) {
			startActivity(new Intent(MainActivity.this, NoticeActivity.class));
		}
		if (v.getId() == R.id.img_profile_menu6) {
			startActivity(new Intent(MainActivity.this, TglobeAppActivity.class));
		}

		if (v.getId() == R.id.img_profile_menu7) {
			startActivity(new Intent(MainActivity.this,
					MyDiscountActivity.class));
		}
		if (v.getId() == R.id.img_profile_menu8) {
			startActivity(new Intent(MainActivity.this, MySettingActivity.class));
		}
		if (v.getId() == R.id.img_profile_menu9) {
			
			Control.Loginstatus=false;

			SharedPreferences sharedpreferences = getSharedPreferences("Tglobe", Context.MODE_PRIVATE);	
			
			Control.UserName="";
			Control.UserPassword="";
			
			Editor editor = sharedpreferences.edit();
			editor.putString("Username", Control.UserName);
			editor.putString("Password", Control.UserPassword);
			
			
			Log.e("tglobe","======Logout=======");

			Log.e("tglobe",sharedpreferences.getString("Username", ""));
			Log.e("tglobe",sharedpreferences.getString("Password", ""));
			
			MainActivity.this.finish();
			startActivity(new Intent(MainActivity.this, LoginActivity.class));
		}

		if (v.getId() == R.id.img_user) {

			startActivity(new Intent(MainActivity.this, MyprofileActivity.class));
		}

		// ===============

	}

	// ===============Animation
	@Override
	public void onScrollEnded() {
		// TODO Auto-generated method stub
		Log.e("TG", "onScrollEnded()");

	}

	
	private int countLoadData=0;
	@Override
	public void onScrollStarted() {

		Log.e("TG", "onScrollStarted()");
		
		if(countLoadData%2==0)
		{
			setListview_notis();
		}
		countLoadData++;

	}
	
	
	
	
	class LoadData_Notification extends AsyncTask<Object, Integer, Object> {

		
		
		boolean Cancelled=false;
		
		
		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub]
			Cancelled=true;
			super.onCancelled();
		}
		@SuppressWarnings("null")
		@Override
		protected Object doInBackground(Object... params) {

			
			
			
				
				 
				 
				 
				 try {
						
						JSONObject jsonObj=null;
						jsonObj = new JSONObject(HttpGetJson.GetJson(Control.getAPI_Notification(),Control.user,Control.pass));
						
						
						JSONArray jsonarray_data=jsonObj.getJSONArray("notification_notice");
						 for (int i = 0; i <jsonarray_data.length(); i++)
						 { 
							 
							 map_notis = new HashMap<String, Object>();
							 JSONObject jsonObj_data=jsonarray_data.getJSONObject(i);

							
							 map_notis.put("title",jsonObj_data.getString("title"));
							 map_notis.put("detail",jsonObj_data.getString("desc"));
							 map_notis.put("type","notice");

							// map.put("date_promotion",jsonObj_data.getString("date_promotion"));
			
						     MyArrList_notis.add(map_notis);
						     runOnUiThread (new Thread(new Runnable() { 
						         public void run() {
						                adapter_notis.notifyDataSetChanged();      
						                

										Log.e("TG", " adapter.notifyDataSetChanged();  ");
						         }
						     }));
						 }
						
						 JSONArray jsonarray_data2=jsonObj.getJSONArray("notification_tglobeapp");
						 for (int i = 0; i <jsonarray_data2.length(); i++)
						 { 
							 
							 map_notis = new HashMap<String, Object>();
							 JSONObject jsonObj_data=jsonarray_data2.getJSONObject(i);

							 map_notis.put("title",jsonObj_data.getString("title"));
							 map_notis.put("detail",jsonObj_data.getString("desc"));
							 map_notis.put("type","tglobeapp");
			
						     MyArrList_notis.add(map_notis);
						     runOnUiThread (new Thread(new Runnable() { 
						         public void run() {
						                adapter_notis.notifyDataSetChanged();      
						                

										Log.e("TG", " adapter.notifyDataSetChanged();  ");
						         }
						     }));
						 }
						 
						 JSONArray jsonarray_data3=jsonObj.getJSONArray("notification_discount");
						 for (int i = 0; i <jsonarray_data3.length(); i++)
						 { 
							 
							 map_notis = new HashMap<String, Object>();
							 JSONObject jsonObj_data=jsonarray_data3.getJSONObject(i);

							 map_notis.put("title",jsonObj_data.getString("title"));
							 map_notis.put("detail",jsonObj_data.getString("desc"));
							 map_notis.put("type","discount");
			
						     MyArrList_notis.add(map_notis);
						     runOnUiThread (new Thread(new Runnable() { 
						         public void run() {
						                adapter_notis.notifyDataSetChanged();      
						                

										Log.e("TG", " adapter.notifyDataSetChanged();  ");
						         }
						     }));
						 }
						 
						 
						 
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			
				 
			return null;
		}

		@Override
		protected void onPreExecute() {

			MyArrList_notis.clear();
			adapter_notis=null;
			
			if (adapter_notis == null) {
				adapter_notis = new NotificationAdapter(MainActivity.this, MyArrList_notis);
				lstView_notis.setAdapter(adapter_notis);
				
				Log.e("TG", "adapter = new NotiListAdapter(getActivity(), MyArrList);");
				
			}

			
			super.onPreExecute();
		}

		@Override
		public void onProgressUpdate(Integer... progress) {

			Log.e("star", "progressupdate");
			
			
		}

		@Override
		protected void onPostExecute(Object result) {
		
			if(!Cancelled)
			{
				
			}
			
		}

	}


	private void Chk_InvisibleLay() {
		// TODO Auto-generated method stub

		int i = 0;
		while (i < indexAll) {
			if (i <= indexPage)
				Lay_content[i].setVisibility(View.INVISIBLE);
			i++;
		}
	}

	@Override
	public void onAnimationEnd(Animation animation) {
		// TODO Auto-generated method stub
		Log.e("TG", "Animation End");
		if (next) {

			Chk_InvisibleLay();
		}

		if (next) {

			indexPage++;

		} else {
			indexPage--;

		}
		Log.e("TG", "indexPage=" + indexPage);

		// ============arrow chk

		if (indexPage == 0)
			img_back_content.setVisibility(View.INVISIBLE);
		else
			img_back_content.setVisibility(View.VISIBLE);

		if (indexPage == indexAll)
			img_next_content.setVisibility(View.INVISIBLE);
		else
			img_next_content.setVisibility(View.VISIBLE);

	}

	@Override
	public void onAnimationRepeat(Animation animation) {
		// TODO Auto-generated method stub
		Log.e("TG", "Animation onAnimationRepeat");
	}

	@Override
	public void onAnimationStart(Animation animation) {
		// TODO Auto-generated method stub

		if (!next) {
			Lay_content[indexPage - 1].setVisibility(View.VISIBLE);
		}

		if (next) {
			int i = 0;
			while (i < indexAll) {
				if (i < indexPage)
					Lay_content[i].setVisibility(View.INVISIBLE);
				i++;
			}
		}
		Log.e("TG", "Animation onAnimationStart");
	}

	
	
	
	
	
	
	
	// ================SetProfileMenu====================
	
	private void SetViewProfile() {
		// TODO Auto-generated method stub
	

		Laylogin = (FrameLayout) findViewById(R.id.Laylogin);
		if (!Control.Loginstatus)
			Laylogin.setVisibility(View.VISIBLE);

		// =======menu
		img_profile_menu1 = (ImageView) findViewById(R.id.img_profile_menu1);
		img_profile_menu2 = (ImageView) findViewById(R.id.img_profile_menu2);
		img_profile_menu3 = (ImageView) findViewById(R.id.img_profile_menu3);
		img_profile_menu4 = (ImageView) findViewById(R.id.img_profile_menu4);
		img_profile_menu5 = (ImageView) findViewById(R.id.img_profile_menu5);
		img_profile_menu6 = (ImageView) findViewById(R.id.img_profile_menu6);
		img_profile_menu7 = (ImageView) findViewById(R.id.img_profile_menu7);
		img_profile_menu8 = (ImageView) findViewById(R.id.img_profile_menu8);
		img_profile_menu9 = (ImageView) findViewById(R.id.img_profile_menu9);

		
		TextView txt_username=(TextView) findViewById(R.id.txt_username);
		txt_username.setText(Control.UserName.replace("%20"," "));
				
		
		img_user = (ImageView) findViewById(R.id.img_user);
		img_user.setOnClickListener(this);

		img_profile_menu1.setOnClickListener(this);
		img_profile_menu2.setOnClickListener(this);
		img_profile_menu3.setOnClickListener(this);
		img_profile_menu4.setOnClickListener(this);
		img_profile_menu5.setOnClickListener(this);
		img_profile_menu6.setOnClickListener(this);
		img_profile_menu7.setOnClickListener(this);
		img_profile_menu8.setOnClickListener(this);
		img_profile_menu9.setOnClickListener(this);

		// =========Login
		txt_next = (LinearLayout) findViewById(R.id.txt_next);
		txt_next.setOnClickListener(this);

		txt_register = (LinearLayout) findViewById(R.id.txt_register);
		txt_register.setOnClickListener(this);

		ImageView img_tglobe_login = (ImageView) findViewById(R.id.img_tglobe_login);
		img_tglobe_login.setOnClickListener(this);

		ImageView img_facebook = (ImageView) findViewById(R.id.img_facebook);
		img_facebook.setOnClickListener(this);
		
		
		if (Control.Loginstatus)
		{
			Log.e("Picasso", "=========Picasso() ==========");
			try {
				
				
				
				Log.e("Picasso", "=========Picasso() ==========");
				
				if(Control.Img_profile.equals(""))
				{
					img_user.setImageResource(R.drawable.btn_menu_top_righ);

				}
				else
				{
					Bitmap myBitmap = BitmapFactory.decodeFile(Control.Img_profile_Path);
					img_user.setImageBitmap(myBitmap);

				}
				
				
				
				} catch (Exception e) {
					img_user.setImageResource(R.drawable.btn_menu_top_righ);

				}
		}
		

	}

	
	
	
}
